<template>
  <div class="main">
    <div ref="DataDistributionPie" class="main-chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { findDataDistribution } from "@/api/data";

const DataDistributionPie = ref(null);

// 定义响应式数据
const distributionData = ref([]);

// 获取数据的方法
const fetchData = async () => {
  try {
    const res = await findDataDistribution();
    // 根据后端返回的数据格式更新分布数据
    distributionData.value = [
      // { value: res.data.flux, name: "通量" },
      { value: res.data.meteorology, name: "气象" },
      // { value: res.data.sif, name: "荧光" },
      { value: res.data.phenology, name: "物候" },
      // { value: res.data.other, name: "其他" },
    ];
  } catch (error) {
      // 根据后端返回的数据格式更新分布数据
      distributionData.value = [
        // { value: 1000, name: "通量" },
        { value: 600, name: "气象" },
        // { value: 100, name: "荧光" },
        { value: 300, name: "物候" },
        // { value: 10, name: "其他" },
      ];
      console.error("获取数据失败", error);
  }
};

// 初始化图表的方法
const initChart = () => {
  // 如果数据还未加载，不进行初始化
  if (!distributionData.value.length) {
    console.warn("Data is not loaded yet. Skipping chart initialization.");
    return;
  }

  const myChart = echarts.init(DataDistributionPie.value);

  const option = {
    title: {
      text: "观测场数据分布情况",
      left: "center",
      fontSize: 18,
      textStyle: {
        color: "#1e90ff",
      },
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      //横向布局
      orient: "horizontal",
      //水平居中
      left: "center",
      bottom: "5%",
      itemWidth: 12,
      itemHeight: 6,
      itemGap: 5,
      textStyle: {
        color: "#1e90ff",
        fontSize: 12,
      },
    },
    series: [
      {
        name: "条数",
        type: "pie",
        radius: "50%",
        center: ["50%", "50%"],
        label: {
          show: true,
          fontWeight: "lighter",
          fontSize: 12,
          color: "#f1f2f6",
          formatter: "{b} ({d}%)",
        },
        data: distributionData.value, // 使用最新的数据
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  myChart.setOption(option);

  // 监听窗口变化，自适应大小
  window.addEventListener("resize", () => {
    myChart.resize();
  });
};

// 挂载时先获取数据，再初始化图表
onMounted(async () => {
  await fetchData(); // 等待数据加载完成
  initChart(); // 初始化图表
});
</script>

<style scoped lang="scss">
.main {
  height: 100%;
  width: 100%;
  .main-chart {
    display: flex;
    width: 100%;
    height: 100%;
  }
}
</style>